/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-03-20 17:13:42
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-03-21 20:40:05
 * @FilePath: \react-jike\src\pages\Article\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useState, useEffect, useMemo, useCallback } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Select,
  DatePicker,
  Table,
  Tag,
  Space,
  Popconfirm
} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { getArticleList, deleteArticle } from '@/apis/article';
import useChannels from '@/hooks/useChannels';
import { PUBLISH_STATUS, PUBLISH_STATUS_TEXT, PUBLISH_STATUS_COLOR } from '@/contants';

import img404 from '@/assets/error.png';

import './index.scss';

const { Option } = Select;
const { RangePicker } = DatePicker;

const Article = () => {
  const navagite = useNavigate();
  // 频道列表
  const { channelList } = useChannels();
  // 文章列表数据管理
  const [article, setArticleList] = useState({
      list: [],
      count: 0
  });
  // 分页配置
  const [pageConfig, setPageConfig] = useState({
    // 当前页码(默认为1)
    page: 1,
    // 当前页条数(默认为10)
    per_page: 10
  });

  const fetchArticleList = useCallback(
    async (params = {}) => {
      try {
        const reqData = {
          ...params,
          page: pageConfig.page,
          per_page: pageConfig.per_page
        };
        const { results, total_count } = await getArticleList(reqData);
        setArticleList({
          list: results,
          count: total_count
        });
      }
      catch (error) {
        console.log(error);
      }
    },
    [pageConfig]
  );

  const handleFinish = useCallback(
    values => {
      // 1. 准备参数
      const { status, channel_id, date} = values;
      // 时间段
      const [startTime = null, endTime = null] = date || [];
      const reqData = {
        // 文章状态: 0-草稿, 1-待审核, 2-审核通过, 3-审核失败, 不传为全部(指的参数名也不携带)
        status,
        // 不传为全部(指的不传递此参数名)
        channel_id,
        // 起始时间(指的想让后台从哪个时间开始往后返回数据), 格式年-月-日
        begin_pubdate: startTime ? startTime.format('YYYY-MM-DD') : startTime,
        // 截止时间(指的想让后台返回到哪个时间之前的数据), 格式年-月-日
        end_pubdate: endTime ? endTime.format('YYYY-MM-DD') : endTime
      };
      // 2. 使用参数获取新的列表
      fetchArticleList(reqData);
    },
    [fetchArticleList]
  );

  const handleDelete = useCallback(
    async data => {
      await deleteArticle(data);
      setPageConfig({
        ...pageConfig,
        page: 1,
        per_page: 10
      });
    },
    [pageConfig]
  );

  const handlePageChange = useCallback(
    (page, per_page) => {
      // 拿到当前页参数 修改params 引起接口更新
      setPageConfig({
        ...pageConfig,
        page,
        per_page
      })
    },
    [pageConfig]
  );


  // 准备列数据
  const columns = useMemo(
    () => {
      return [
        {
          title: '封面',
          dataIndex: 'cover',
          width: 120,
          render: cover => {
            return <img src={cover.images[0] || img404} width={80} height={60} alt="" />
          }
        },
        {
          title: '标题',
          dataIndex: 'title',
          width: 220
        },
        {
          title: '状态',
          dataIndex: 'status',
          render: status => {
            const color = PUBLISH_STATUS_COLOR?.[status];
            const text = PUBLISH_STATUS_TEXT?.[status];
            return <Tag color={color}>{ text }</Tag>;
          }
        },
        {
          title: '发布时间',
          dataIndex: 'pubdate'
        },
        {
          title: '阅读数',
          dataIndex: 'read_count'
        },
        {
          title: '评论数',
          dataIndex: 'comment_count'
        },
        {
          title: '点赞数',
          dataIndex: 'like_count'
        },
        {
          title: '操作',
          render: data => {
            return (
              <Space size="middle">
                <Button
                  type="primary"
                  shape="circle"
                  icon={<EditOutlined />}
                  onClick={() => navagite(`/publish?id=${data.id}`)}
                />
                <Popconfirm
                  title="确认删除该条文章吗?"
                  onConfirm={() => handleDelete(data)}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button
                    type="primary"
                    danger
                    shape="circle"
                    icon={<DeleteOutlined />}
                  />
                </Popconfirm>
              </Space>
            )
          }
        }
      ];
    },
    [handleDelete, navagite]
  );

  useEffect(
    () => {
      fetchArticleList()
    },
    [fetchArticleList]
  );

  return (
    <div className='article-page-container'>
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: '文章列表' },
          ]} />
        }
        style={{ marginBottom: 20 }}
      >
        <Form
          initialValues={{ status: '' }}
          onFinish={handleFinish}
        >
          <Form.Item label="状态" name="status">
            <Select placeholder="请选择状态" style={{ width: 200 }} >
              {
                PUBLISH_STATUS.map(item => {
                  return (
                    <Option key={item.value} value={item.value}>
                      {item.label}
                    </Option>
                  )
                })
              }
            </Select>
          </Form.Item>

          <Form.Item label="频道" name="channel_id" >
            <Select placeholder="请选择频道" style={{ width: 200 }} >
              {
                channelList.map(item => {
                  return (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  )
                })
              }
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            {/* 传入locale属性 控制中文显示*/}
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
              筛选
            </Button>
          </Form.Item>
        </Form>
        <Card title={`根据筛选条件共查询到 ${article.count} 条结果：`}>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={article.list}
            pagination={{
              current: pageConfig.page,
              pageSize: pageConfig.per_page,
              onChange: handlePageChange,
              total: article.count
            }}
          />
        </Card>
      </Card>
    </div>
  )
}
export default Article;